//
//  NDTabBarView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/7.
//

import SwiftUI
import SwiftUIIntrospect

let mainNav = "main"
struct NDTabBarView: View {
    @State private var selectedTab: Int = 0
    @State private var isTabBarHidden: Bool = false // 控制显示/隐藏
    
    private let tabItems: [NDTabItem] = WJAppEnvironment.shared.currentCountry == .india ? [
        NDTabItem(title: nil,
                  normalIcon: "home_normal",
                  selectedIcon: "home_selected",
                  color: Color(hex: "#FFFFFF")),
        NDTabItem(title: nil,
                  normalIcon: "order_list_normal",
                  selectedIcon: "order_list_selected",
                  color: Color(hex: "#FFFFFF")),
        NDTabItem(title: nil,
                  normalIcon: "calculator_normal",
                  selectedIcon: "calculator_selected",
                  color: Color(hex: "#FFFFFF")),
        NDTabItem(title: nil,
                  normalIcon: "mine_normal",
                  selectedIcon: "mine_selected",
                  color: Color(hex: "#FFFFFF")),
    ] : [
        NDTabItem(title: nil,
                  normalIcon: "home_normal",
                  selectedIcon: "home_selected",
                  color: Color(hex: "#FFFFFF")),
        NDTabItem(title: nil,
                  normalIcon: "order_list_normal",
                  selectedIcon: "order_list_selected",
                  color: Color(hex: "#FFFFFF")),
        NDTabItem(title: nil,
                  normalIcon: "mine_normal",
                  selectedIcon: "mine_selected",
                  color: Color(hex: "#FFFFFF")),
    ]
    
    var body: some View {
        NavigationView {
            ZStack(alignment: .bottom) {
                // 内容区域
                TabView(selection: $selectedTab) {
//                    NavigationView {
                        NDHomeView()
                            .tag(0)
//                    }
//                    .tag(0)
                    
                    NavigationView {
                        NDOrderContentView()
                    }
                    .tag(1)
                    
                    if WJAppEnvironment.shared.currentCountry == .india {
                        
                        NavigationView {
                            NDCalculatorView()
                        }
                        .tag(2)

                        NavigationView {
                            NDMineView()
                        }
                        .tag(3)
                    } else {
                        NavigationView {
                            NDMineView()
                        }
                        .tag(2)
                    }
                }
                .introspect(.tabView, on: .iOS(.v13, .v14, .v15, .v16, .v17, .v18, .v26)) { tabView in
                    // 隐藏系统 TabBar
                    tabView.tabBar.isHidden = true
                }
                
                // 自定义TabBar
                HStack(spacing: 0) {
                    ForEach(0..<tabItems.count, id: \.self) { index in
                        NDTabButton(
                            item: tabItems[index],
                            isSelected: selectedTab == index
                        ) {
                            
                            NDLocationManager.shared.requestLocationPermission { isAccess in
                                if WJAppEnvironment.shared.currentCountry == .indonesia {
                                    guard isAccess else { return }
                                }
                                selectedTab = index
                                
                                if WJAppEnvironment.shared.currentCountry == .india {
                                    if index == 0 {
                                        NotificationCenter.default.post(name: .schemeRefreshHome, object: nil)
                                    } else if index == 1 {
                                        NotificationCenter.default.post(name: .schemeRefreshOrderList, object: nil)
                                        
                                    } else if index == 3 {
                                        NotificationCenter.default.post(name: .schemeRefreshMine, object: nil)
                                    }
                                } else {
                                    if index == 0 {
                                        NotificationCenter.default.post(name: .schemeRefreshHome, object: nil)
                                    } else if index == 1 {
                                        NotificationCenter.default.post(name: .schemeRefreshOrderList, object: nil)
                                    } else if index == 2 {
                                        NotificationCenter.default.post(name: .schemeRefreshMine, object: nil)
                                    }
                                }
                            }
                        }
                        .frame(maxWidth: .infinity)
                        .frame(height: AppConstants.tabBarHeight)
                    }
                }
                .background(Color(hex: "#FFFFFF"))
                .clipShape(Capsule())  // 使用 Capsule 自动裁剪为半圆
                .overlay(
                    Capsule()  // 边框也用 Capsule
                        .stroke(Color(hex: "#000000"), lineWidth: 1)
                )
                .accessibilityHidden(isTabBarHidden)
                .padding(.horizontal, 25)
                .padding(.bottom, 18)
            }
            .ignoresSafeArea()
        }
        .onAppear {
            // 监听通知
            setupNotificationObserver()
        }
        .onDisappear {
            // 移除监听
            NotificationCenter.default.removeObserver(self)
        }
        .navigationViewManager(for: mainNav, afterBackDo: {
            print("返回到tabBar")
        })
        .introspect(.navigationView(style: .stack), on: .iOS(.v13, .v14, .v15, .v16, .v17, .v18, .v26)) { navigationController in
            // 关键：存储导航控制器
            NavigationControllerStore.shared.storeNavigationController(navigationController, for: mainNav)
        }
    }
    
    // 设置通知监听
    private func setupNotificationObserver() {
        NotificationCenter.default.addObserver(
            forName: .updateTabBarVisibility,
            object: nil,
            queue: .main
        ) { notification in
            // 立即更新状态，无延迟
            if let isHidden = notification.userInfo?[TabBarVisibilityKeys.isHidden] as? Bool {
                self.isTabBarHidden = isHidden
            }
        }
        
        NotificationCenter.default.addObserver(
            forName: .switchTab,
            object: nil,
            queue: .main
        ) { notification in
            if let tabIndex = notification.userInfo?[TabSwitchKeys.tabIndex] as? Int {
                withAnimation(.easeOut) {
                    self.selectedTab = tabIndex
                }
            }
        }
    }
}

struct TabSwitchKeys {
    static let tabIndex = "tabIndex"
}

struct NDTabItem {
    let title: String?
    let normalIcon: String?
    let selectedIcon: String?
    let color: Color
}

// 预览
struct NDTabBarView_Previews: PreviewProvider {
    static var previews: some View {
        NDTabBarView()
    }
}
